package com.ibm.moa.outmail.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import org.json.JSONObject;
import org.json.XML;

import android.content.Context;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.ibm.moa.outmail.R;
import com.ibm.moa.outmail.module.MailProvider;
import com.ibm.moa.outmail.module.MailProvider.Providers;
import com.ibm.moa.outmail.module.MailProvider.Providers.Provider;

public class MailUtils {
	private static Providers mProviders;

	public static void init(Context context) {
		InputStream is = null;
		BufferedReader br = null;
		InputStreamReader isr = null;
		String result = null;
		try {
			is = context.getResources().openRawResource(R.raw.providers);
			isr = new InputStreamReader(is, "utf-8");
			br = new BufferedReader(isr);
			String line = null;
			StringBuffer sb = new StringBuffer();
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
			result = sb.toString();
			JSONObject providersObj = XML.toJSONObject(result);
			if (providersObj != null) {
				MailProvider mailProvider = JSON.parseObject(providersObj.toString(), MailProvider.class);
				Providers mProviders = mailProvider.getProviders();
				setmProviders(mProviders);
			}
			System.out.println(result);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			com.alibaba.fastjson.util.IOUtils.close(br);
			com.alibaba.fastjson.util.IOUtils.close(isr);
			com.alibaba.fastjson.util.IOUtils.close(is);
		}

	}

	public static Providers getProviders() {
		return mProviders;
	}

	private static void setmProviders(Providers mProviders) {
		MailUtils.mProviders = mProviders;
	}

	public static Provider getProviderByDomail(String domain) {
		if (TextUtils.isEmpty(domain) || mProviders == null) {
			return null;
		}
		final List<Provider> pList = mProviders.getProvider();
		if (pList == null) {
			return null;
		}
		for (Provider p : pList) {
			if (p != null && domain.equals(p.getDomain())) {
				return p;
			}
		}
		return null;
	}
}
